package com.example.assetmanagement.config;

import com.example.assetmanagement.domain.User;
import com.example.assetmanagement.mapper.UserMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

@Component
@RequiredArgsConstructor
public class DefaultAdminInitializer implements ApplicationRunner {

    private final UserMapper userMapper;
    private final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

    @Override
    public void run(ApplicationArguments args) throws Exception {
        User existing = userMapper.selectByUsername("admin");
        String defaultRaw = "123456";
        if (existing == null) {
            User admin = new User();
            admin.setUsername("admin");
            admin.setPassword(passwordEncoder.encode(defaultRaw));
            admin.setFullName("系统管理员");
            admin.setStatus(1);
            userMapper.insert(admin);
            System.out.println("Created default admin user -> username: admin, password: 123456");
        } else if (!passwordEncoder.matches(defaultRaw, existing.getPassword())) {
            // 若已存在但密码不同，重置为默认密码
            existing.setPassword(passwordEncoder.encode(defaultRaw));
            userMapper.update(existing);
            System.out.println("Reset admin password to default: 123456");
        }
    }
} 